﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;

namespace PADWH35
{
    public partial class WORWorkOrderPAD : Form
    {
        DataTable dtsourse = new DataTable();
        DataTable dtTmpSource = new DataTable();
        public WORWorkOrderPAD()
        {
            InitializeComponent();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            label2.Text = "当前时间：" + DateTime.Now.ToString() + " " + GetDayName() + "\r\n";
        }

        private string GetDayName()
        {
            string result = "";
            DateTime today = DateTime.Now;
            if (today.DayOfWeek == DayOfWeek.Monday)
            {
                result = "星期一";
            }
            else if (today.DayOfWeek == DayOfWeek.Tuesday)
            {
                result = "星期二";
            }
            else if (today.DayOfWeek == DayOfWeek.Wednesday)
            {
                result = "星期三";
            }
            else if (today.DayOfWeek == DayOfWeek.Thursday)
            {
                result = "星期四";
            }
            else if (today.DayOfWeek == DayOfWeek.Friday)
            {
                result = "星期五";
            }
            else if (today.DayOfWeek == DayOfWeek.Saturday)
            {
                result = "星期六";
            }
            else if (today.DayOfWeek == DayOfWeek.Sunday)
            {
                result = "星期日";
            }
            return result;
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void refreshData()
        {
            try
            {
                string sql_getJobNum = "SELECT Key1 FROM ice.ud21 WHERE Company = 'NSZ' AND Key5 = 'JobNumWorkOrder'";
                var jnDt = DBHelper.ExecuteDt(sql_getJobNum);
                List<string> jobNums = new List<string>();
                foreach (DataRow row in jnDt.Rows)
                {
                    jobNums.Add(row["key1"].ToString());
                }
                string JN = "(";
                foreach (string jobNum in jobNums)
                {
                    JN += "'" + jobNum + "'" + ",";
                }
                JN = JN.Substring(0, JN.Length - 1);
                JN += ")";
                //DataTable jnQtyDt = new DataTable();
                //if (jobNums.Count()>0)
                //{
                //    string sql_getQty = $"SELECT SUM(TRY_CONVERT(INT,Key2)) sqty,Key1 JobNum FROM ice.ud21  WHERE Company='NSZ'AND key5='jobQty'AND Key1 in {JN}  GROUP BY Key1";
                //     jnQtyDt = DBHelper.ExecuteDt(sql_getQty);
                //}
                string sql_getData = $@"SELECT 
                                   f.工单号 ,
                                   f.工单类型 ,                                  
                                   f.生产方式 ,
                                   f.订单号,
                                   f.物料编码 ,
                                   f.物料描述 ,
                                   f.创建日期 ,
                                   f.需求日期 ,
                                   f.开始日期 ,
                                   f.工单数量 ,
                                   CAST(round(AVG([配套比]),2) AS NVARCHAR)+'%'[配套比],
                                   f.是否缺料,
                                   f.已完成数量 ,
                                   f.已入库数量 ,
                                   f.工序 
                            FROM (
                            SELECT  a.JobNum [工单号] ,
                                    ( CASE a.ShortChar06
                                      WHEN N'Normal-常规工单' THEN N'常规工单'
                                      WHEN N'Re-work-返工工单' THEN N'返工工单'
                                      WHEN N'Mold Trial-试模工单' THEN N'试模工单'
                                      WHEN N'Mold Mfg(New)-新模工单' THEN N'新模工单'
                                      WHEN N'Mold Mfg(Modification)-改模工单' THEN N'改模工单'
                                      WHEN N'Mold Mfg(Repair)-修模工单' THEN N'修模工单'
                                      ELSE a.ShortChar06
                                      END ) [工单类型] ,
                                    a.PartNum [物料编码] ,
                                    ( CASE d.OrderNum
                                        WHEN '0' THEN N'备货生产'
                                        ELSE N'按单生产'
                                      END ) [生产方式] ,
                                    ( CASE d.OrderNum
                                        WHEN '0' THEN NULL
                                        ELSE d.OrderNum
                                      END ) [订单号] ,
                                    a.PartDescription [物料描述] ,
                                     (' '+CAST(a.CreateDate AS nvarchar)+' ')   [创建日期] ,
                                    (' '+CAST(a.ReqDueDate AS nvarchar)+' ') [需求日期] ,
                                    (' '+CAST(a.StartDate  AS nvarchar)+' ')[开始日期] ,
                                    (SELECT CAST(a.ProdQty AS int)) [工单数量] ,
                                    (CASE WHEN e.RequiredQty<>0 THEN CAST((e.IssuedQty/e.BaseRequiredQty)*100 AS INT) ELSE 0 END) [配套比],                              
                                    (CASE WHEN CAST(e.BaseRequiredQty AS DECIMAL)>(CAST(g.OnhandQty AS DECIMAL)+CAST(e.IssuedQty AS DECIMAL)) THEN N'是' ELSE N'否' end) [是否缺料],                                    
                                    (SELECT CAST(a.QtyCompleted AS int))[已完成数量],
                                    (SELECT CAST(d.ReceivedQty AS int)) [已入库数量],
                                    b.OpDtlDesc [工序] 
                            FROM    JobHead a
                                    LEFT JOIN ( SELECT  Company ,
                                                        JobNum ,
                                                        ResourceGrpID ,
                                                        OpDtlDesc
                                                FROM    Erp.JobOpDtl
                                                GROUP BY Company ,
                                                        JobNum ,
                                                        ResourceGrpID ,
                                                        OpDtlDesc
                                              ) b ON b.Company = a.Company
                                                     AND b.JobNum = a.JobNum
                                    LEFT JOIN ResourceGroup c ON b.Company = c.Company
                                                                 AND b.ResourceGrpID = c.ResourceGrpID
                                    LEFT JOIN Erp.JobProd d ON a.Company = d.Company
                                                               AND a.JobNum = d.JobNum
                                    LEFT JOIN JobMtl e ON a.JobNum= e.JobNum AND a.Company=e.Company
                                    LEFT JOIN (SELECT SUM(OnhandQty) OnhandQty,PartNum,Company FROM  Erp.PartBin  GROUP BY PartNum,Company)g ON e.PartNum=g.PartNum AND e.Company=g.Company
                            WHERE   c.JCDept = 'WOR'
                                    AND a.Company = 'NSZ'
                                    AND a.JobClosed = 0 ";

                if (jobNums.Count > 0)
                {
                    sql_getData += $@"AND a.JobNum in {JN} ";
                }
                else
                {
                    sql_getData += $@" AND a.JobNum ='' ";
                }
                sql_getData += @"  ) f
                            GROUP BY 
                                     f.工单号 ,
                                   f.工单类型 ,
                                   f.物料编码 ,
                                   f.生产方式 ,
                                   f.订单号 ,
                                   f.物料描述 ,
                                   f.创建日期 ,
                                   f.需求日期 ,
                                   f.开始日期 ,
                                   f.工单数量 ,
                                   f.已完成数量 ,
                                   f.是否缺料,
                                   f.已完成数量,
                                   f.已入库数量 ,
                                   f.工序 
                             ORDER BY f.工单号
                            ";
                dtsourse = DBHelper.ExecuteDt(sql_getData);
                if (dtsourse.Rows.Count > 0)
                {
                    DataRow[] drs1 = new DataRow[] { };
                    List<string> jbNs = new List<string>();
                    string temp = "";
                    string tempType = "";

                    List<DataRow> a = new List<DataRow>();
                    foreach (DataRow dr in dtsourse.Rows)
                    {
                        string jbN = dr["工单号"].ToString();
                        string jbType = dr["生产方式"].ToString();
                        if (jbN == temp && jbType == tempType)
                        {
                            jbNs.Add(jbN);
                            if (a.Count > 0)
                            {
                                a.Remove(a.Last());
                            }
                        }
                        else
                        {
                            a.Add(dr);
                        }
                        temp = jbN;
                        tempType = jbType;
                    }
                    DataTable dt = new DataTable();
                    if (jbNs.Count > 0)
                    {
                        string str = "(";
                        foreach (var jbn in jbNs)
                        {
                            str += $"工单号 = '{jbn}' or ";
                        }
                        str = str.Substring(0, (str.Length - 3));
                        str += ") and 是否缺料 = '是'";
                        drs1 = dtsourse.Select(str);
                    }
                    if (drs1.Count() > 0)
                    {

                        foreach (var tep in drs1)
                        {
                            a.Add(tep);
                        }
                    }
                    drs1 = a.ToArray();



                    if (drs1 != null && drs1.Length > 0)
                    {
                        DataTable tmp = drs1[0].Table.Clone();
                        foreach (DataRow row in drs1)
                        {
                            tmp.ImportRow(row); // 将DataRow添加到DataTable中
                        }
                        dtsourse = tmp;
                    }
                }
                //if (dtsourse.Rows.Count > 0)
                //{
                //    foreach (DataRow row in dtsourse.Rows)
                //    {
                //        string jobNum = row["工单号"].ToString();

                //        DataRow[] qty = new DataRow[] { };
                //        if (jnQtyDt.Rows.Count>0)
                //        {
                //             qty = jnQtyDt.Select($"JobNum='{jobNum}'");
                //        }

                //        if (qty.Count() > 0)
                //        {
                //            row["已完成数量"] =(qty[0])["sqty"].ToString();
                //        }

                //    }
                //}
                int m = dataGridView1.DisplayedRowCount(true);
                if (dtTmpSource.Rows.Count == dtsourse.Rows.Count)
                {

                    List<string> a = new List<string>();
                    for (int i = 0; i < dtsourse.Rows.Count; i++)
                    {
                        a.Add(dtsourse.Rows[i][0].ToString());
                    }
                    for (int i = 0; i < dtsourse.Rows.Count; i++)
                    {

                        if (!a.Contains(dtTmpSource.Rows[i][0].ToString()))
                        {
                            dtTmpSource = dtsourse;
                            dataGridView1.DataSource = dtsourse;
                            refreshColor();
                        }
                    }

                }
                else
                {
                    dtTmpSource = dtsourse;
                    dataGridView1.DataSource = dtsourse;
                    refreshColor();
                }
                if (dataGridView1.RowCount > 0)
                {
                    dataGridView1.Columns["物料描述"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;

                    dataGridView1.Columns["工序"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
                    //dataGridView1.Columns["创建日期"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
                    //dataGridView1.Columns["需求日期"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
                    //dataGridView1.Columns["开始日期"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
                    dataGridView1.Columns["是否缺料"].Visible = false;
                    dataGridView1.Columns["工序"].Visible = false;
                }
            }
            catch (Exception ex)
            {
                WriteLog.Writelog("刷新数据错误！  "+ex.ToString());
            }

        }

        private void refreshColor()
        {
            try
            {
                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {
                    string tatal = dataGridView1.Rows[i].Cells["配套比"].Value.ToString();
                    string date1 = dataGridView1.Rows[i].Cells["需求日期"].Value.ToString();
                    string date2 = dataGridView1.Rows[i].Cells["开始日期"].Value.ToString();

                    if (!string.IsNullOrEmpty(tatal) && !string.IsNullOrEmpty(date1) && !string.IsNullOrEmpty(date2))
                    {
                        date1 = date1.Substring(1, 10);
                        date2 = date2.Substring(1, 10);
                        if (Convert.ToDateTime(date1) < Convert.ToDateTime(date2))
                        {
                            dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.Red;
                        }
                        else if (dataGridView1.Rows[i].Cells["是否缺料"].Value.ToString() == "是")
                        {
                            dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.Yellow; ;
                        }
                        else
                        {
                            dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.Green;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                WriteLog.Writelog("刷新颜色错误！  " + ex.ToString());
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                refreshData();
                dataGridView1.ClearSelection();
                this.WindowState = FormWindowState.Maximized;
                if (dataGridView1.RowCount > 0)
                {
                    dataGridView1.Columns["物料描述"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;

                    dataGridView1.Columns["工序"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
                    //dataGridView1.Columns["创建日期"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
                    //dataGridView1.Columns["需求日期"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
                    //dataGridView1.Columns["开始日期"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
                    dataGridView1.Columns["是否缺料"].Visible = false;
                    label3.Font = new Font("宋体", 30, FontStyle.Bold);
                }
                WriteLog.Writelog("程序启动成功！");
            }
            catch (Exception ex)
            {
                WriteLog.Writelog(ex.ToString());
               
            }
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            refreshData();
            dataGridView1.ClearSelection();
        }

        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Escape)
            {
                DialogResult dr = MessageBox.Show("确定退出？", "提示！", MessageBoxButtons.YesNo);
                if (dr == DialogResult.Yes)
                {
                    WriteLog.Writelog("程序已关闭！");
                    this.Close();
                }
            }
        }

        private void vScrollBar1_Scroll(object sender, ScrollEventArgs e)
        {
            //dataGridView1.FirstDisplayedScrollingRowIndex = e.NewValue;
            //if (vScrollBar1.Value < dataGridView1.Rows.Count)
            //    dataGridView1.FirstDisplayedScrollingRowIndex = e.NewValue;

            //if (vScrollBar1.Value == vScrollBar1.Maximum)
            //    dataGridView1.FirstDisplayedScrollingRowIndex = e.NewValue - 1;
        }


        private void vScrollBar1_ValueChanged(object sender, EventArgs e)
        {
            //if (vScrollBar1.Maximum > 0)
            //{
            //    if (vScrollBar1.Value < dataGridView1.Rows.Count)
            //        dataGridView1.FirstDisplayedScrollingRowIndex = vScrollBar1.Value;

            //    if (vScrollBar1.Value == vScrollBar1.Maximum)
            //        dataGridView1.FirstDisplayedScrollingRowIndex = vScrollBar1.Value - 1;
            //}
        }
        protected override void OnMouseWheel(MouseEventArgs e)
        {
            //base.OnMouseWheel(e);
            //if (0 < vScrollBar1.Value && vScrollBar1.Value < vScrollBar1.Maximum)
            //{
            //    if (e.Delta < 0)
            //    {
            //        vScrollBar1.Value += vScrollBar1.LargeChange;
            //    }
            //    else
            //    {
            //        vScrollBar1.Value -= vScrollBar1.LargeChange;
            //    }
            //    VerticalScroll.Value = vScrollBar1.Value;
            //}
        }

        private void dataGridView1_Click(object sender, EventArgs e)
        {
            // vScrollBar1.Focus();
        }

        private void dataGridView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            refreshColor();
        }


        private void timer3_Tick(object sender, EventArgs e)
        {
            if (dtTmpSource.Rows.Count > 0)
            {
                var row = dtTmpSource.Rows[0].ItemArray;
                dtTmpSource.Rows.Add(row);
                dtTmpSource.Rows.RemoveAt(0);
                dataGridView1.DataSource = dtTmpSource;
                dataGridView1.ClearSelection();
                refreshColor();
            }
            //if (dataGridView1.RowCount < 22)
            //{
            //    return;
            //}
            ////dgvcasebystreet为DataGridVew控件 
            //int index = this.dataGridView1.FirstDisplayedScrollingRowIndex;
            //this.dataGridView1.Rows[index].Selected = true;  // 设置为选中.
            //this.dataGridView1.FirstDisplayedScrollingRowIndex++;
            ////如果数据太少.就不滚动 

            ////将刚才定位的数据插入到dtSource的末尾.这是为了实现循环滚动. 
            ////dtsourse.ImportRow(dtsourse.Rows[index]);
            ////rowCount为记录总数 
            //if (this.dataGridView1.FirstDisplayedScrollingRowIndex > (dtTmpSource.Rows.Count - 22))
            //{
            //    //初始时,将数据取出同时放在dtSource   与dtTmpSource中, 
            //    //现在dtSource中,已增加了很多数据. 
            //    //因而在所有原数据都遍历完,开始下一次遍历时,将原数据覆盖现在的dtSource   ; 
            //    dtsourse = dtTmpSource;
            //    dataGridView1.ClearSelection();
            //    this.dataGridView1.FirstDisplayedScrollingRowIndex = 0;
            //}
            //下面注释掉代码,只是用来说明程序中是如何绑定数据的.
            //BindingSource bindSrc = new BindingSource();
            //bindSrc.Clear();
            //bindSrc.DataSource = dtSource;//该dtSource为存放数据的dataTable对象 
            //this.dgvcasebystreet.DataSource = bindSrc;

            //this.dataGridView1.CurrentCell = this.dataGridView1.Rows[row].Cells[0];
            //if(row< dataGridView1.RowCount)
            //{
            //    row++;
            //}
        }

        private void dataGridView1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {
                contextMenuStrip1.Show(PointToScreen(e.Location));
            }
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            WriteLog.Writelog("程序已关闭！ ");
            this.Close();
        }

        private void label1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {
                contextMenuStrip1.Show(PointToScreen(e.Location));
            }
        }

        private void label2_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {
                contextMenuStrip1.Show(PointToScreen(e.Location));
            }
        }

        private void dataGridView1_MouseEnter(object sender, EventArgs e)
        {
            timer3.Stop();
        }

        private void dataGridView1_MouseLeave(object sender, EventArgs e)
        {
            timer3.Start();
        }
    }
}
